﻿using Abp;
using Abp.Domain.Uow;
using GN.Pay.Core.Services.Impl;
using RabbitMQ.GNClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace GN.Pay.Core.Tasks.Queue.Impl
{
    /// <summary>
    /// 
    /// </summary>
    abstract class AQueue : APayService, IQueue
    {
        private const string queuefx = "gn.pay.";

        private IMQConnection connection;
        private IMQChannel channel;

        /// <summary>
        /// 实例化 AQueue 类新实例
        /// </summary>
        /// <param name="name"></param>
        public AQueue(string name)
        {
            this.Name = queuefx + name.ToLowerInvariant();
        }

        /// <summary>
        /// 获取名称
        /// </summary>
        public string Name { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected IMQChannel GetChannel()
        {
            lock (this)
            {
                if (channel != null)
                {
                    return channel;
                }
                if (channel == null)
                {
                    if (connection == null)
                    {
                        connection = QueueFactory.CreateConnection();
                    }
                }
                channel = connection.CreateChannel(this.Name);
                return channel;
            }            
        }

        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }       

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isDispose"></param>
        protected virtual void Dispose(bool isDispose)
        {
            if (isDispose)
            {
                if (channel != null)
                {
                    channel.Dispose();
                }
                if (connection != null)
                {
                    connection.Dispose();
                }
            }
        }


    }
}
